"""
# -*- coding:utf-8 -*-
@Project : telegramBot
@software: PyCharm
@File : test01.py
@author:  wade
@IDE NAME: PyCharm
@Time : 2025/6/11 13:03
@
"""
import asyncio
import json
import threading

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
# import threading
from tools.db_connect import MySQLCRUD

# 导入BotTools
from tools.BotTools import BotTools

# 实例化BotTools
bt = BotTools()

# 实例化数据量连接
db = MySQLCRUD()

# 替换为你的 Bot 的 API 令牌
TOKEN = "5961536453:AAFlghpF5shm0g-pPiHKrhfmF9pKVT05Z8k"


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """处理 /start 命令"""
    await update.message.reply_text("Hello! I'm your keyword - based assistant. Type something to get started.")


async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """处理 /help """
    user_id = update.message.from_user.id
    await update.message.reply_text(f'当前UID是：{user_id}')


async def wadedong(update: Update, context: ContextTypes.DEFAULT_TYPE):
    '''TEST def '''
    user_test = update.message.text.split(' ')[1]
    print(user_test)
    await update.message.reply_text(f'这是一个测试命令: {user_test}')


# async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
async def handle_message(update: Update, context):
    """处理用户消息，检测关键字并执行操作"""
    user_message = update.message
    print(user_message)
    print(user_message.forward_origin)
    # print(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))
    # 检测消息中的关键字
    # 下载 TG 中的内容到本地

    if user_message.text:
        if 'https://t.me' in user_message.text:
            print("命中 TDL 下载")
            url_list = {url.strip() for url in user_message.text.strip('"').split('\n')}  # 如果有多个连接将连接 存放到 集合中 中逐个下载
            if '' in url_list:
                url_list.remove('')
            await context.bot.send_message(chat_id=update.effective_chat.id, text='检测到tg内容下载链接，开始处理下载')

            try:
                def run_async_task():
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    try:
                        loop.run_until_complete(bt.tdl_download(url_list))
                    finally:
                        loop.close()

                thread = threading.Thread(target=run_async_task)
                thread.start()

            except Exception as e:
                await context.bot.send_message(chat_id=update.effective_chat.id, text=f'下载貌似出错了{e}')

            await context.bot.send_message(chat_id=update.effective_chat.id, text='下载成功后会发送Push消息到手机')

        # 查询天气
        elif '天气' in user_message.text:
            print("命中 天气 查询")
            await context.bot.send_message(chat_id=update.effective_chat.id, text='正在查询天气')
            await context.bot.send_photo(chat_id=update.effective_chat.id,
                                         photo='https://img.xiaobi195.com/contents/videos_screenshots/127000/127660/180x135/2.jpg')
            await context.bot.send_video(chat_id=update.effective_chat.id, )

        elif 'kdw' in user_message.text:
            print("命中 蝌蚪窝 搜索")
            keyword = user_message.text.split()[1]

            datas = db.read(table='video_info', where=f'name LIKE "%{keyword}%" ORDER BY score DESC limit 5')
            for data in datas:
                name = data.get('name')
                img = data.get('img')
                path = 'https://www.xiaobi168.com/' + data.get('path')

                await context.bot.send_photo(chat_id=update.effective_chat.id, photo=img, caption=name)
                await context.bot.send_message(chat_id=update.effective_chat.id, text=path)
        else:
            await context.bot.send_message(chat_id=update.effective_chat.id, text='没太明白你要让我干啥')


    elif user_message.video:
        print("命中 视频消息 下载")
        print(f'获取到的了视频消息：{user_message.video.duration}')
        print(user_message.video.file_name)
        print(user_message.video.file_size)


async def get_video_info(update: Update, context):
    user_message = update.message
    print(user_message)
    print("*" * 100)
    print(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))
    print("*" * 100)

    print("命中 视频消息 下载")
    # print(f'获取到的了视频消息：{user_message.video.duration}')
    # print(user_message.video.file_name)
    # print(user_message.video.file_size)

    chat_id = user_message.chat.id
    chat_name = user_message.chat.title
    message_id = user_message.message_id
    video_name = user_message.video.file_name

    print(f'视频内容是：\n 频道ID：{chat_id},频道名称：{chat_name}，消息ID：{message_id}，视频名称：{video_name}')
    print(f"拼接的视频下载地址是：https://t.me/c/{chat_id}/{message_id}")


if __name__ == "__main__":
    app = Application.builder().token(TOKEN).build()

    # 添加命令处理器
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("help", help))
    app.add_handler(CommandHandler("test", wadedong))

    # 添加消息处理器，用于处理用户的消息
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))  # 处理文本类消息
    app.add_handler(MessageHandler(filters.ALL, get_video_info))  # 处理所有类型消息

    # 开始轮询，监听消息
    print("Bot started...")
    app.run_polling()
